#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tornado.web
import json
import logging
from datetime import datetime


class BaseHandler(tornado.web.RequestHandler):
    """基础处理器类"""
    
    def set_default_headers(self):
        """设置默认响应头"""
        self.set_header("Content-Type", "application/json; charset=utf-8")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "Content-Type")
        self.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
    
    def options(self, *args, **kwargs):
        """处理 OPTIONS 请求"""
        self.set_status(204)
        self.finish()
    
    def write_json(self, data, status_code=200):
        """返回 JSON 响应"""
        self.set_status(status_code)
        self.write(json.dumps(data, ensure_ascii=False, indent=2))
        self.finish()


class MainHandler(BaseHandler):
    """主页处理器"""
    
    def get(self):
        """处理 GET 请求"""
        data = {
            "message": "欢迎使用 Tornado 后端服务",
            "timestamp": datetime.now().isoformat(),
            "version": "1.0.0",
            "endpoints": {
                "home": "/",
                "api": "/api/hello",
                "health": "/health",
                "calc": "/api/calc"
            }
        }
        self.write_json(data)


class ApiHandler(BaseHandler):
    """API 处理器"""
    
    def get(self):
        """处理 GET 请求"""
        name = self.get_argument("name", "World")
        data = {
            "message": f"Hello, {name}!",
            "method": "GET",
            "timestamp": datetime.now().isoformat()
        }
        self.write_json(data)
    
    def post(self):
        """处理 POST 请求"""
        try:
            # 尝试解析 JSON 数据
            if self.request.headers.get("Content-Type", "").startswith("application/json"):
                data = json.loads(self.request.body.decode("utf-8"))
            else:
                data = {}
            
            response_data = {
                "message": "POST request received",
                "received_data": data,
                "method": "POST",
                "timestamp": datetime.now().isoformat()
            }
            self.write_json(response_data)
            
        except json.JSONDecodeError:
            error_data = {
                "error": "Invalid JSON format",
                "message": "Please send valid JSON data"
            }
            self.write_json(error_data, 400)
        except Exception as e:
            error_data = {
                "error": "Internal server error",
                "message": str(e)
            }
            self.write_json(error_data, 500)


class HealthHandler(BaseHandler):
    """健康检查处理器"""
    
    def get(self):
        """健康检查"""
        data = {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "uptime": "running"
        }
        self.write_json(data)


class CalcHandler(BaseHandler):
    """计算处理器"""
    
    def get(self):
        """计算 1+1"""
        result = 1 + 1
        data = {
            "calculation": "1 + 1",
            "result": result,
            "timestamp": datetime.now().isoformat()
        }
        self.write_json(data)
